﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace API.Models.Repository
{
    public class LOCATIONS_Repository : GenericRepository<PartnerDbContext, WH_LOCATIONS>
    {
        public override IQueryable<WH_LOCATIONS> Find(System.Linq.Expressions.Expression<Func<WH_LOCATIONS, bool>> predicate)
        {
            IQueryable<WH_LOCATIONS> query = _entities.WH_LOCATIONS;

            if (predicate != null)
                query = query.Where(predicate);

            if (session != null)
            {
                query = query
                    .ToList()
                    .Where(r => r.COMPANY_GUID == session.COMPANY_GUID)
                    .AsQueryable();
            }

            return query;
        }

        public override void Add(WH_LOCATIONS entity)
        {
            var record = this.Find(r =>
                    r.COMPANY_GUID == this.session.COMPANY_GUID &&
                    r.EXT_KEY == entity.EXT_KEY)
                .SingleOrDefault();

            if (record != null)
            {
                record.BUILDING_NUMBER = entity.BUILDING_NUMBER;
                record.CITY = entity.CITY;
                record.COUNTRY = entity.COUNTRY;
                record.EXT_KEY = entity.EXT_KEY;
                record.IS_DEFAULT = entity.IS_DEFAULT;
                record.LOCATION_NAME = entity.LOCATION_NAME;
                record.NOTE = entity.NOTE;
                record.POSTAL_CODE = entity.POSTAL_CODE;
                record.STREET = entity.STREET;

                this.Edit(record);
                return;
            }

            if (entity.GUID_RECORD == null || entity.GUID_RECORD == Guid.Empty)
                entity.GUID_RECORD = Guid.NewGuid();

            entity.COMPANY_GUID = this.session.COMPANY_GUID;

            _entities.Set<WH_LOCATIONS>().Add(entity);
        }

        public override void Edit(WH_LOCATIONS entity)
        {
            entity.COMPANY_GUID = this.session.COMPANY_GUID;

            try
            {
                if (_entities.Entry(entity).State == System.Data.EntityState.Modified)
                {
                    _entities.Entry(entity).CurrentValues.SetValues(entity);
                }

                _entities.Entry(entity).State = System.Data.EntityState.Modified;
            }
            catch
            {
                /// В случае повторного обновления записи
                /// возникает ошибка
                /// нужно как-то обработать. Но как?
            }
        }
    }
}